import Request from 'luch-request'
import { BAST_URL, WHITE_LIST } from './constant'
import { useUserStore } from '@/store/user'
const request = new Request({
    baseURL: BAST_URL,
    custom: {
        loading: true
    }
})
request.interceptors.request.use((config) => {
    //开启弹层
    if (config.custom?.loading === true) {
        uni.showLoading({
            title: '正在加载中...',
            mask: true
        })
    }
    //
    const store = useUserStore()
    if (store.token && !WHITE_LIST.includes(config.url as string)) {
        config.header!.Authorization = `Bearer ${store.token}`
    }
    return config
}, (error) => {
    return Promise.reject(error)
})
request.interceptors.response.use((res) => {
    //关闭弹层
    uni.hideLoading()
    if (res.data.code !== 10000) {
        uni.showToast({
            title: res.data.message,
            icon: 'none'
        })
        return Promise.reject(res.data)
    }
    return res.data?.data
}, (error) => {
    //关闭弹层
    uni.hideLoading()
    // console.log(error);
    uni.showToast({
        title: error.data.message,
        icon: 'none'
    })
    if(error.statusCode){
        uni.reLaunch({
            url:'/pages/login/index'
        })
    }
    return Promise.reject(error.data)
})
export { request }
